package com.ellricky.baselib.ui.cla

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.andr.common.ui.fragment.BaseFragment
import com.andr.common.ui.mvp.BasePresenter
import com.ellricky.baselib.BaseConstant.*
import com.ellricky.baselib.R
import com.ellricky.baselib.adapter.cla.ClassManageAdapter
import com.ellricky.baselib.adapter.cla.ClassRoomAdapter
import com.ellricky.baselib.cache.LocalCacheUtil
import com.ellricky.baselib.entity.IdNameEntity
import com.ellricky.baselib.entity.new.ClassEntry
import com.ellricky.baselib.http.HttpUtils
import com.ellricky.baselib.listener.OnClassPersonListener
import com.ellricky.baselib.ui.student.StudentDetailActivity
import com.ellricky.baselib.ui.teacher.EvaluateStudentActivity
import com.ellricky.baselib.util.EAppUtil
import com.ellricky.baselib.util.NewECallback
import com.ellricky.baselib.util.NewEListCallback
import com.ellricky.baselib.util.jump
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener
import com.scwang.smartrefresh.layout.listener.OnRefreshListener
import com.yanzhenjie.recyclerview.OnItemMenuClickListener
import com.yanzhenjie.recyclerview.SwipeMenuCreator
import com.yanzhenjie.recyclerview.SwipeMenuItem
import com.yanzhenjie.recyclerview.SwipeRecyclerView
import kotlinx.android.synthetic.main.base_frg_class_manage.*
import java.text.SimpleDateFormat
import java.util.*

class ClassManageFragment : BaseFragment<Void, BasePresenter<Void>>(),
    AdapterView.OnItemClickListener, OnRefreshListener, OnLoadMoreListener,
    OnClassPersonListener {


    companion object {
        fun newInstance(home: Boolean = true): ClassManageFragment {
            val fragment = ClassManageFragment()
            val bundle = Bundle()
            bundle.putBoolean("home", home)
            fragment.arguments = bundle
            return fragment
        }
    }


    private var home = false

    private lateinit var roomAdapter: ClassRoomAdapter
    private lateinit var classAdapter: ClassManageAdapter

    override fun getContentLayout() = R.layout.base_frg_class_manage

    override fun initUIView(view: View?) {
        home = arguments?.getBoolean("home", false) ?: false
        initRv()

        val data = Date(System.currentTimeMillis())
        val format = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA)
        weekDate = format.format(data)
    }

    private fun initRv() {
        rvClaRoom.layoutManager = LinearLayoutManager(mContext, RecyclerView.HORIZONTAL, false)
        roomAdapter = ClassRoomAdapter(mContext)
        roomAdapter.setOnItemClickListener(this)
        rvClaRoom.adapter = roomAdapter
        roomList?.let {
            roomAdapter.refresh(it)
        }

        slClass.setEnableLoadMoreWhenContentNotFull(false)
        slClass.setOnRefreshListener(this)
        slClass.setOnLoadMoreListener(this)

        rvClass.layoutManager = LinearLayoutManager(mContext)
        rvClass.setOnItemMenuClickListener(mItemMenuClickListener) // Item的Menu点击。
        rvClass.setSwipeMenuCreator(mSwipeMenuCreator) // 菜单创建器。

        classAdapter = ClassManageAdapter(mContext, classRoomType, this)
        rvClass.adapter = classAdapter
    }

///////////////////////////////////////////////////////////////////////////
// 请求
///////////////////////////////////////////////////////////////////////////

    var weekDate: String? = ""
    var classRoomType: String = "" //评估列表 与 班级管理
    private var roomList: MutableList<IdNameEntity>? = null
    var classRoomId: String? = null

    fun loadClassRooms() {
        val url = EAppUtil.getApiHost()
        val paramMap = hashMapOf<String, String>()
        paramMap["action"] = getActions()
        paramMap["school_id"] = LocalCacheUtil.getSchoolId()
        paramMap["eid"] = LocalCacheUtil.getUid()
        paramMap["class_date"] = weekDate ?: ""
        HttpUtils.getInstance()
            .postFrom(url, paramMap, object : NewEListCallback<IdNameEntity>(mContext, false) {
                override fun onSuccess(data: MutableList<IdNameEntity>?, msg: String?) {
                    if (data.isNullOrEmpty()) {
                        roomList = data
                        roomAdapter.refresh(roomList)
                        slClass.visibility = View.INVISIBLE
                    } else {
                        roomList = data
                        roomAdapter.refresh(roomList)
                        classRoomId = roomAdapter[0].id

                        slClass.visibility = View.VISIBLE
                        loadClassList()
                    }
                }

                override fun onErrorCode(code: String?, msg: String?) {
                    super.onErrorCode(code, msg)
                    roomList = mutableListOf()
                    roomAdapter.refresh(roomList)
                    slClass.visibility = View.INVISIBLE
                }
            })
    }

    private fun getActions(): String {
        when (LocalCacheUtil.getCardType()) {
            CARD_TEACHER_MANAGER -> {
                return "gzaClassRoomList"
            }
            CARD_TEACHER -> {
                return "classRoomList"
            }
            CARD_PRESIDENT -> {
                return "headClassRoomList"
            }
            CARD_CONSULTANT -> {
                return "saleClassRoomList"
            }
        }
        return ""
    }

    private fun getClassRoomActions(): String {
        when (LocalCacheUtil.getCardType()) {
            CARD_TEACHER_MANAGER -> {
                return "gzaClassGradeStateList"
            }
            CARD_TEACHER -> {
                return "classGradeStateList"
            }
            CARD_PRESIDENT -> {
                return "headClassGradeStateList"
            }
            CARD_CONSULTANT -> {
                return "saleClassGradeStateList"
            }
        }
        return ""
    }

    private fun loadClassList() {
        val url = EAppUtil.getApiHost()
        val paramMap = hashMapOf<String, String>()
        paramMap["action"] = getClassRoomActions()
        paramMap["school_id"] = LocalCacheUtil.getSchoolId()
        paramMap["eid"] = LocalCacheUtil.getUid()
        paramMap["class_date"] = weekDate ?: ""
        paramMap["room_id"] = classRoomId ?: ""

        HttpUtils.getInstance()
            .postFrom(url, paramMap, object : NewEListCallback<ClassEntry>(mContext, false) {
                override fun onSuccess(data: MutableList<ClassEntry>?, msg: String?) {
                    data?.forEach {
                        val s1ClassEntry = it.S_1?.filter { it.is_job_ok == "0" }
                        val s2ClassEntry = it.S_2?.filter { it.is_job_ok == "0" }
                        if (s1ClassEntry != null || s2ClassEntry != null) {
                            if (activity != null) {
                                val classManageActivity = activity as? ClassManageActivity
                                classManageActivity?.showTips()
                            }
                        }
                    }
                    slClass.finishRefresh()
                    classAdapter.dataSource.clear()
                    classAdapter.dataSource.addAll(data ?: mutableListOf())
                    classAdapter.notifyDataSetChanged()
                }

                override fun onErrorCode(code: String?, msg: String?) {
                    super.onErrorCode(code, msg)
                    classAdapter.dataSource.clear()
                    classAdapter.notifyDataSetChanged()
                    slClass.finishRefresh(false)
                }

                override fun onHttpError(code: String?, msg: String?) {
                    super.onHttpError(code, msg)
                    classAdapter.dataSource.clear()
                    classAdapter.notifyDataSetChanged()
                    slClass.finishRefresh(false)
                }
            })
    }


///////////////////////////////////////////////////////////////////////////
// 分页
///////////////////////////////////////////////////////////////////////////

    override fun onRefresh(refreshLayout: RefreshLayout) {
        loadClassRooms()
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {

    }

///////////////////////////////////////////////////////////////////////////
//  侧滑删除
///////////////////////////////////////////////////////////////////////////

    /**
     * 菜单创建器。
     */
    private val mSwipeMenuCreator = SwipeMenuCreator { _, swipeRightMenu, position ->
        val width = resources.getDimensionPixelSize(R.dimen.dp_70)

        // 1. MATCH_PARENT 自适应高度，保持和Item一样高;
        // 2. 指定具体的高，比如80;
        // 3. WRAP_CONTENT，自身高度，不推荐;
        val height = resources.getDimensionPixelSize(R.dimen.base_dp_class_manage_top)

        // 添加右侧的，如果不添加，则右侧不会出现菜单。
        val deleteItem = SwipeMenuItem(mContext)
            .setBackground(R.drawable.base_bg_menu_del)
            .setText("删除")
            .setTextSize(12)
            .setTextColor(Color.WHITE)
            .setWidth(width)
            .setHeight(height)
        swipeRightMenu.addMenuItem(deleteItem)// 添加一个按钮到右侧侧菜单。
    }

    /**
     * RecyclerView的Item的Menu点击监听。
     */
    private val mItemMenuClickListener = OnItemMenuClickListener { menuBridge, position ->
        menuBridge.closeMenu()
        val direction = menuBridge.direction // 左侧还是右侧菜单。
        val menuPosition = menuBridge.position // 菜单在RecyclerView的Item中的Position。
        if (direction == SwipeRecyclerView.RIGHT_DIRECTION) {
            when (menuPosition) {
                0 -> delClass(position)
            }
        }
    }

    private fun delClass(position: Int) {
        val url = EAppUtil.getApiHost()
        val paramMap = hashMapOf<String, String>()
        paramMap["action"] = "gzaDeleteClassGrade"
        paramMap["class_grade_id"] = classAdapter.dataSource[position].class_id ?: ""
        paramMap["course_list_id"] = classAdapter.dataSource[position].course_list_id ?: ""
        paramMap["eid"] = LocalCacheUtil.getUid()
        HttpUtils.getInstance().postFrom(url, paramMap, object : NewECallback<Any>(mContext) {
            override fun onSuccess(data: Any?, msg: String?) {
                classAdapter.dataSource.removeAt(position)
                classAdapter.notifyItemRemoved(position)
            }
        })
    }

///////////////////////////////////////////////////////////////////////////
// 教室列表点击事件
///////////////////////////////////////////////////////////////////////////

    override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        roomAdapter.curPos = position
        roomAdapter.notifyDataSetChanged()
        classRoomId = roomAdapter[position].id
        loadClassList()
    }


    override fun jumpPersonModify(entity: ClassEntry) {
        val intent = Intent(mContext, PersonModifyActivity::class.java)
        intent.putExtra("course_list_id", entity.course_list_id)
        intent.putExtra("openDate", weekDate)
        intent.putExtra("classId", entity.class_id)
        EAppUtil.jumpForResult(this, intent)
    }

    override fun jumpStuAdd(entity: ClassEntry, sortNo: String) {
        val intent = Intent(mContext, StuAddActivity::class.java)
        intent.putExtra("course_list_id", entity.course_list_id)
        intent.putExtra("classId", entity.class_id)
        intent.putExtra("sortNo", sortNo)
        intent.putExtra("class_type_dic_id", entity.class_type_dic_id)
        EAppUtil.jumpForResult(this, intent)
    }

    override fun jumpTcAdd(entity: ClassEntry, sortNo: String) {
        val intent = Intent(mContext, TeacherAddActivity::class.java)
        intent.putExtra("course_list_id", entity.course_list_id)
        intent.putExtra("classId", entity.class_id)
        intent.putExtra("sortNo", sortNo)
        EAppUtil.jumpForResult(this, intent)
    }


    override fun jumpStuDetail(stuId: String, stuName: String, courseListId: String) {
        if (classRoomType == TYPE_EVALUATE) {
            jump<EvaluateStudentActivity> {
                putExtra(KEY_ID, stuId)
                putExtra(KEY_NAME, stuName)
                putExtra(KEY_IDs, courseListId)
            }
        } else {
            EAppUtil.jumpPageWithId(this, StudentDetailActivity::class.java, stuId)
        }
    }

    override fun dealBkLogic(
        classId: String,
        hasBk: Boolean,
        preId: String
    ) {
//        when (isOperation) {
//            "1" -> {
//                // 教师自己
//                when (hasBk) {
//                    true -> {
//                        // 进入备课详情
//                        EAppUtil.jumpPageWithId(this, PreLessonDetailActivity::class.java, preId)
//                    }
//                    false -> {
//                        // 去备课
//                        EAppUtil.jumpPreLessonSave(this, classId, openDate)
//                    }
//                }
//            }
//            else -> {
//                // 非教师自己
//                when (hasBk) {
//                    true -> {
//                        // 进入备课详情
//                        EAppUtil.jumpPageWithId(this, PreLessonDetailActivity::class.java, preId)
//                    }
//                }
//            }
//        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (resultCode) {
            RESULT_CODE_ADD, RESULT_CODE_DEL, RESULT_CODE_CREATE -> loadClassList()
        }
    }
}

